package ar.drools.apuestas.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import ar.drools.apuestas.modelo.Piloto;
import ar.drools.apuestas.modelo.ResultadosCarrera;
import ar.drools.apuestas.persistencia.HibernateUtil;

public class HTMLParser {

	public static List<Piloto> obtenerPilotosConDatos() {
		
		Session session = HibernateUtil.getSessionFactory().openSession();
        
		List<Piloto> listaPilotos = new ArrayList<Piloto>();
		Map<String, List<String>> pilotos = new HashMap<String, List<String>>();

		String basicUrl = "http://www.statsf1.com/es/";
		String complexUrl = "/grand-prix.aspx";

		pilotos.put("Sebastian Vettel", new ArrayList<String>(Arrays.asList(basicUrl + "sebastian-vettel.aspx", basicUrl + "sebastian-vettel" + complexUrl)));
		pilotos.put("Mark Webber", new ArrayList<String>(Arrays.asList(basicUrl + "mark-webber.aspx", basicUrl + "mark-webber" + complexUrl)));
		pilotos.put("Fernando Alonso", new ArrayList<String>(Arrays.asList(basicUrl + "fernando-alonso.aspx", basicUrl + "fernando-alonso" + complexUrl)));
		pilotos.put("Felipe Massa", new ArrayList<String>(Arrays.asList(basicUrl + "felipe-massa.aspx", basicUrl + "felipe-massa" + complexUrl)));
		pilotos.put("Jenson Button", new ArrayList<String>(Arrays.asList(basicUrl + "jenson-button.aspx", basicUrl + "jenson-button" + complexUrl)));
		pilotos.put("Sergio Perez", new ArrayList<String>(Arrays.asList(basicUrl + "sergio-perez.aspx", basicUrl + "sergio-perez" + complexUrl)));
		pilotos.put("Kimi Raikkonen", new ArrayList<String>(Arrays.asList(basicUrl + "kimi-raikkonen.aspx", basicUrl + "kimi-raikkonen" + complexUrl)));
		pilotos.put("Romain Grosjean", new ArrayList<String>(Arrays.asList(basicUrl + "romain-grosjean.aspx", basicUrl + "romain-grosjean" + complexUrl)));
		pilotos.put("Nico Rosberg", new ArrayList<String>(Arrays.asList(basicUrl + "nico-rosberg.aspx", basicUrl + "nico-rosberg" + complexUrl)));
		pilotos.put("Lewis Hamilton", new ArrayList<String>(Arrays.asList(basicUrl + "lewis-hamilton.aspx", basicUrl + "lewis-hamilton" + complexUrl)));
		pilotos.put("Paul Di Resta", new ArrayList<String>(Arrays.asList(basicUrl + "paul-di-resta.aspx", basicUrl + "paul-di-resta" + complexUrl)));
		pilotos.put("Adrian Sutil", new ArrayList<String>(Arrays.asList(basicUrl + "adrian-sutil.aspx", basicUrl + "adrian-sutil" + complexUrl)));
		pilotos.put("Nico Hulkenberg", new ArrayList<String>(Arrays.asList(basicUrl + "nico-hulkenberg.aspx", basicUrl + "nico-hulkenberg" + complexUrl)));
		pilotos.put("Esteban Gutierrez", new ArrayList<String>(Arrays.asList(basicUrl + "esteban-gutierrez.aspx", basicUrl + "esteban-gutierrez" + complexUrl)));
		pilotos.put("Pastor Maldonado", new ArrayList<String>(Arrays.asList(basicUrl + "pastor-maldonado.aspx", basicUrl + "pastor-maldonado" + complexUrl)));
		pilotos.put("Valteri Bottas", new ArrayList<String>(Arrays.asList(basicUrl + "valtteri-bottas.aspx", basicUrl + "valtteri-bottas" + complexUrl)));
		pilotos.put("Daniel Ricciardo", new ArrayList<String>(Arrays.asList(basicUrl + "daniel-ricciardo.aspx", basicUrl + "daniel-ricciardo" + complexUrl)));
		pilotos.put("Jean Eric Vergne", new ArrayList<String>(Arrays.asList(basicUrl + "jean-eric-vergne.aspx", basicUrl + "jean-eric-vergne" + complexUrl)));
		pilotos.put("Charles Pic", new ArrayList<String>(Arrays.asList(basicUrl + "charles-pic.aspx", basicUrl + "charles-pic" + complexUrl)));
		pilotos.put("Giedo Van Der Garde", new ArrayList<String>(Arrays.asList(basicUrl + "giedo-van-der-garde.aspx", basicUrl + "giedo-van-der-garde" + complexUrl)));
		pilotos.put("Jules Bianchi", new ArrayList<String>(Arrays.asList(basicUrl + "jules-bianchi.aspx", basicUrl + "jules-bianchi" + complexUrl)));
		pilotos.put("Max Chilton", new ArrayList<String>(Arrays.asList(basicUrl + "max-chilton.aspx", basicUrl + "max-chilton" + complexUrl)));

		try {
			for (Map.Entry<String, List<String>> piloto : pilotos.entrySet()) {
				
				Piloto nuevo = (Piloto) session.get(Piloto.class, piloto.getKey());
				if(nuevo == null){
					nuevo = new Piloto();
					nuevo.setNombre(piloto.getKey());
	
					Document doc = Jsoup.connect(piloto.getValue().get(0)).get();
					Document docDiv = null;
					Elements divs = doc.select("div");
					for (Element div : divs) {
						if (div.hasClass("piloteitem")) {
							docDiv = Jsoup.parse(div.outerHtml());
							Elements divsInternos = docDiv.select("div");
							for (Element divInterno : divsInternos) {
								Elements anchorInternos = divInterno.select("a");
								for (Element anchorInterno : anchorInternos) {
									if (anchorInterno.attr("id").toUpperCase().contains("STATSGP") && (nuevo.getCantidadCarrerasCorridas()==null || nuevo.getCantidadCarrerasCorridas().compareTo(new Double("0"))==0) )
										nuevo.setCantidadCarrerasCorridas(Double.parseDouble(anchorInterno.text().substring(0, anchorInterno.text().indexOf("Grandes") - 1)));
									if (anchorInterno.attr("id").toUpperCase().contains("STATSVICTOIRE") && (nuevo.getCantidadCarrerasGanadas()==null || nuevo.getCantidadCarrerasGanadas().compareTo(new Double("0"))==0)  )
										nuevo.setCantidadCarrerasGanadas(Double.parseDouble(anchorInterno.html().split("&nbsp;")[0]));
									if (anchorInterno.attr("id").toUpperCase().contains("STATSABANDON") && (nuevo.getCantidadAbandonos()==null || nuevo.getCantidadAbandonos().compareTo(new Double("0"))==0) )
										nuevo.setCantidadAbandonos(Double.parseDouble(anchorInterno.html().split("&nbsp;")[0]));
								}
							}
	
						}
					}
	
					Document doc2 = Jsoup.connect(piloto.getValue().get(1)).get();
					Document docTR = null;
					Elements tables = doc2.select("table");
					for (Element table : tables) {
						if (table.hasClass("sortable")) {
							String tableHTML = table.outerHtml();
							docTR = Jsoup.parse(tableHTML);
							Elements trs = docTR.select("tbody tr");
							for (Element tr : trs) {
								Elements tds = tr.select("td");
								for (int i = 0; i < tds.size(); i = i + 13) {
									ResultadosCarrera rc = new ResultadosCarrera();
									try{rc.setNroCarrera(Double.parseDouble(tds.get(i).text()));}catch(Exception e){}
									try{rc.setParrilla(Double.parseDouble(tds.get(i+10).text()));}catch(Exception e){}
									try{if(tds.get(i+12).text().equals(" ") || tds.get(i+12).html().equalsIgnoreCase("&nbsp;"))rc.setCarrera(Double.parseDouble(tds.get(i+11).text()));}catch(Exception e){}
									nuevo.getResultadosCarrera().add(rc);
								}
							}
						}
					}
					nuevo.calcularUltimasTresCarreras();
					nuevo.calcularClasificadorPrimerosDiez();
					
					session.beginTransaction();
			        session.save(nuevo);
			        session.getTransaction().commit();
				}
		        
				listaPilotos.add(nuevo);
			}

		}

		catch (Exception e) {
			e.printStackTrace();
		}

		return listaPilotos;
	}

}
